<template>
  <div class="app-container">

    <!-- :range="['2022-08-01', '2022-09-04']" -->
    <el-date-picker
      v-model="monthValue"
      type="month"
      size="mini"
      style="width:150px;top: 0px;"
      :clearable="false"
      @change="changeMonth"
    />
    <el-calendar v-model="currentDate">
      <template slot="dateCell" slot-scope="{ date, data }">
        <div>
          <div class="left">
            <el-tag :class="data.isSelected ? 'is-selected' : ''" style="margin-top: 6px;">
              {{
                data.day
                  .split('-')
                  .slice(1)
                  .join('-')
              }}
            </el-tag>
            <!-- 跳过eslint检查 -->
            <!-- eslint-disable -->
            <template v-for="item in ondutyList">
              <!-- eslint-disable -->
              <template
                v-if="item.time && item.time.indexOf(data.day) != -1"
              >
                <el-tag type="success" style="margin-left: 4px;">事件内容:</el-tag>
                <el-popover
                  placement="top-start"
                  trigger="hover"
                  :title="
                    data.day
                      .split('-') 
                      .slice(1)
                      .join('-')
                  "
                >  
                  <div>{{ '事件名称：' + item.name }}</div>
                  <span v-html="item.content"></span>
                  <el-tag type="danger" style="margin-top: 8px;" slot="reference">{{ people(item.name, item.content) }}</el-tag>
                </el-popover>
              </template>
            </template>
            <el-tag v-if="!isIncluded(data)" type="info" style="margin-left: 4px;">事件记录</el-tag>
          </div>
          <div class="right">
            <el-button v-if="data.isSelected && !isIncluded(data)" v-permission="permission.add" size="mini" class="botton" type="primary" @click="add(date)">
              添加
            </el-button>
            <el-button v-if="data.isSelected && isIncluded(data)"  size="mini" class="botton" type="primary" @click="editData(data)">

              编辑
            </el-button>
            <el-button v-if="data.isSelected && isIncluded(data)" v-permission="permission.del" size="mini" class="botton" type="danger" @click="del(data)">
              删除
            </el-button>
          </div>
          <div class="clear" style="clear: both;" />
        </div>
      </template>
    </el-calendar>
    <!--表单组件-->
    <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="500px">
      <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
        <el-form-item label="当前日期" prop="time"><el-date-picker v-model="form.time" disabled type="date" style="width: 370px;" /></el-form-item>
        <el-form-item label="事件名称" prop="name"><el-input v-model.trim="form.name" style="width: 370px;" maxlength="50" /></el-form-item>
        <el-form-item label="事件内容" prop="content"><el-input v-model="form.content" :rows="4" type="textarea" style="width: 370px;" maxlength="250" /></el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="crud.cancelCU">取消</el-button>
        <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import crudOnduty, { getAllData } from '@/api/onduty'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import Date from '@/utils/datetime.js'
const defaultForm = { id: null, time: null, name: null, content: null, deleteFlag: null, createBy: null, updateBy: null, createTime: null, updateTime: null }
export default {
  name: 'Onduty',
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({ title: '事件表', url: 'api/onduty', idField: 'id', sort: 'id,desc', crudMethod: { ...crudOnduty }})
  },
  data() {
    return {
      edit: null,
      permission: {
        add: ['admin', 'onduty:add'],
        del: ['admin', 'onduty:del']
      },
      rules: {
        name: [
          { required: true, message: '事件名称不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '事件名称长度最大为 50 个字符', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '事件内容不能为空', trigger: 'blur' },
          { min: 1, max: 250, message: '事件内容长度最大为 250 个字符', trigger: 'blur' }
        ]
      },
      ondutyList: [{ time: null }],
      currentDate: new Date()
    }
  },

  computed: {
    monthValue: {
      get: function() {
        return this.currentDate
      },
      set: function(newValue) {
        this.currentDate = newValue
      }
    },

    // 字符串超过长度截取，超过15个长度转换成 "..."
    people: function() {
      return function(leader, content) {
        const str = content
        return str.length > 16 ? str.substring(0, 5) + '...' : str
      }
    },

    content: function() {
      return function(data) {
        console.log(data)
        let str = '事件名称：' + data.name + '\n'
        str += '事件内容' + data.content

        return str
      }
    }
  },
  watch: {
    currentDate(nVal, oVal) {
      // 当日期跨过一个月时再次查询
      // 监听日历，时刻获取当前显示页面显示时间的前三十天与后三十天之间的最近六十天数据
      if (nVal && oVal && nVal.getMonth() !== oVal.getMonth()) {
        this.initList(this.getDay(nVal, -30), this.getDay(nVal, 30))
      }
    }
  },
  created() {
    // 获取近60天内的数据
    this.initData()
  },
  methods: {
    initData() {
      this.initList(this.getDay(new Date(), -30), this.getDay(new Date(), 30))
    },
    initList(start, end) {
      getAllData(start, end).then((res) => {
        this.ondutyList = res
      })
    },
    isIncluded(data) {
      let flag = false
      this.ondutyList.forEach((item) => {
        if (item.time && item.time.indexOf(data.day) !== -1) {
          flag = true
        }
      })
      return flag
    },
    changeMonth() {
      this.currentDate = new Date(this.currentDate)
    },
    add(date) {
      defaultForm.time = date
      this.crud.toAdd()
    },
    editData(data) {
      console.log(data)
      const that = this
      that.ondutyList.forEach(res => {
        if (res.time && res.time.indexOf(data.day) !== -1) {
          that.crud.toEdit(res)
        }
      })
    },

    del(data) {
      const that = this
      this.ondutyList.forEach(function(item, index) {
        if (item.time && item.time.indexOf(data.day) !== -1) {
          that
            .$confirm(`确认删除该条数据?`, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            })
            .then(() => {
              var ids = []
              ids.push(item.id)
              that.crud.delAllLoading = true
              crudOnduty.del(ids)
              that.ondutyList.splice(index, 1)
              that.crud.notify('删除成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
            })
            .catch(() => {
            })
        }
      })
    },
    // 获取时间，day为number，getDay(-1):now-1的日期;getDay(0):now的日期;getDay(1):now+1的日期;【以此类推】
    getDay(now, day) {
      var today = new Date(now)
      var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day
      today.setTime(targetday_milliseconds) // 注意，这行是关键代码
      var tYear = today.getFullYear()
      var tMonth = today.getMonth()
      var tDate = today.getDate()
      tMonth = this.doHandleMonth(tMonth + 1)
      tDate = this.doHandleMonth(tDate)
      return tYear + '-' + tMonth + '-' + tDate
    },
    doHandleMonth(month) {
      var m = month
      if (month.toString().length === 1) {
        m = '0' + month
      }
      return m
    },
    /** 提交 - 之后 */
    [CRUD.HOOK.afterSubmit]() {
      // 重新获取数据
      this.initList(this.getDay(this.currentDate, -30), this.getDay(this.currentDate, 30))
    }
  }
}
</script>

<style scoped>
.is-selected {
  color: #1989fa;
}
.left {
  width: 150px;
  display: block;
  float: left;
}
.right {
  width: 60px;
  display: block;
  float: right;
}
.botton {
  margin: 3px 0;
}
</style>
